package lesson02.UDP;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UDPEchoServer01 {

    private DatagramSocket socket;

    public UDPEchoServer01(int port) throws SocketException {
        if (port < 1024 || port > 65535) {
            throw new BindException("端口号必须在1024 —— 65535之间");
        }
        this.socket = new DatagramSocket(port); //自动分配服务器的ip地址
    }

    public void start() throws IOException {
        System.out.println("服务器启动.");
        while (true) {
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);

            String request = new String(requestPacket.getData(),
                    0, requestPacket.getLength(), "UTF-8");

            String response = process(request);

            DatagramPacket respnsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    0, response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(respnsePacket);
            System.out.printf("[%s:%d] request = %s,response=%s\n", requestPacket.getAddress().toString()
                    , requestPacket.getPort(), request, response);
        }
    }

    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer01 udpEchoServer01 = new UDPEchoServer01(9999);
        udpEchoServer01.start();
    }
}
